package com.china08.yxyapi.service.yxyresource.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.transaction.Transactional;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder.Type;
import org.elasticsearch.index.query.RegexpQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.TermsQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.china08.yxyapi.SystemConstant;
import com.china08.yxyapi.api.manage.tec.teaching.lecture.res.LectureUploadResController.ResourceReqModel;
import com.china08.yxyapi.api.manage.tec.teaching.lecture.res.LectureUploadResController.UploadResp;
import com.china08.yxyapi.entity.db.res.YxyResBook;
import com.china08.yxyapi.entity.db.res.YxyResBookContents;
import com.china08.yxyapi.entity.db.res.YxyResBookContentsKnoledges;
import com.china08.yxyapi.entity.db.res.YxyResFormat;
import com.china08.yxyapi.entity.db.res.YxyResPhase;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.db.res.YxyResResourceBookContent;
import com.china08.yxyapi.entity.db.res.YxyResSubject;
import com.china08.yxyapi.entity.db.res.YxyResType;
import com.china08.yxyapi.entity.db.res.YxyResWeikeKnow;
import com.china08.yxyapi.entity.db.yxy.YxyQuesKnow;
import com.china08.yxyapi.entity.es.ElasticYxyResResource;
import com.china08.yxyapi.entity.mg.lecture.YxyLectureRes;
import com.china08.yxyapi.repository.db.YxyQuesKnowRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsKnoledgesRepository;
import com.china08.yxyapi.repository.db.YxyResBookContentsRepository;
import com.china08.yxyapi.repository.db.YxyResBookRepository;
import com.china08.yxyapi.repository.db.YxyResFormatRepository;
import com.china08.yxyapi.repository.db.YxyResPhaseRepository;
import com.china08.yxyapi.repository.db.YxyResResourceBookContentRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.db.YxyResSubjectRepository;
import com.china08.yxyapi.repository.db.YxyResTypeRepository;
import com.china08.yxyapi.repository.db.YxyResWeikeKnowRepository;
import com.china08.yxyapi.repository.db.YxySubjectRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLectureResRepository;
import com.china08.yxyapi.service.yxyresource.YxyResourceLectureService;
import com.china08.yxyapi.util.EsResourceUpdateUtil;
import com.china08.yxyapi.util.WeikeCoverUntil;
import com.china08.yxyapi.util.YxyResUtil;

@Service
public class YxyResourceLectureServiceImpl implements YxyResourceLectureService {

    private static final Logger LOGGER = LoggerFactory.getLogger(YxyResourceLectureServiceImpl.class);

    @Autowired
    private ElasticsearchTemplate et;

    @Autowired
    private YxyResUtil yxyResUtil;

    @Autowired
    private YxyResBookContentsRepository yrbcr;

    @Autowired
    private YxyResFormatRepository yrfr;

    @Autowired
    private YxyResResourceRepository yrrrRepository;

    @Autowired
    private YxyResResourceBookContentRepository yxyResResourceBookContentRepository;

    @Autowired
    private YxyResBookRepository yxyResBookRepository;

    @Autowired
    private YxyLectureResRepository yxyLectureResRepository;

    @Autowired
    private YxyResBookContentsKnoledgesRepository yxyResBookContentsKnoledgesRepository;

    @Autowired
    private YxyResTypeRepository yxyResTypeRepository;

    @Autowired
    private YxyResWeikeKnowRepository yxyResWeikeKnowRepository;

    @Autowired
    private YxyQuesKnowRepository yxyQuesKnowRepository;

    @Autowired
    private YxyResSubjectRepository yxyResSubjectRepository;

    @Autowired
    private YxyResPhaseRepository yxyResPhaseRepository;

    @Autowired
    private YxySubjectRepository yxySubjectRepository;

    // 资源目录
    @Transactional
    private void saveResBookContent(String resId, String bookContentNew) {
        YxyResResourceBookContent resourceBookContent = yxyResResourceBookContentRepository
                .findByResourceIdAndBookContentId(resId, bookContentNew);
        Assert.isNull(resourceBookContent, "已经和这个目录关联了");
        resourceBookContent = new YxyResResourceBookContent();
        resourceBookContent.setResourceId(resId);
        YxyResBookContents bookContents = yrbcr.findById(bookContentNew);
        Assert.notNull(bookContents, "目录未找到请刷新页面");
        resourceBookContent.setBookContentId(bookContents.getId());
        YxyResBook book = yxyResBookRepository.findById(bookContents.getBookId());
        Assert.notNull(book, "书籍未找到请刷新页面");
        // # 找到新目录的书
        String subjectName = book.getSubjectName();
        String versionName = book.getVersionName();
        String phaseName = book.getPhaseName();
        String semesterName = book.getSemersterName();

        resourceBookContent.setSubjectId(book.getSubjectId());
        resourceBookContent.setSubjectName(subjectName);
        resourceBookContent.setVersionId(book.getVersionId());
        resourceBookContent.setVersionName(versionName);
        resourceBookContent.setPhaseId(book.getPhaseId());
        resourceBookContent.setPhaseName(phaseName);
        resourceBookContent.setSemesterId(book.getSemersterId());
        resourceBookContent.setSemesterName(semesterName);
        resourceBookContent.setBookId(book.getId());
        List<YxyResBookContents> parentsBookContents = new ArrayList<YxyResBookContents>();
        parentsBookContents = loopPids(bookContentNew, parentsBookContents);
        List<String> pids = parentsBookContents.stream().map(x -> x.getId()).collect(Collectors.toList());
        List<String> pidNames = parentsBookContents.stream().map(x -> x.getName()).collect(Collectors.toList());
        String bookContentPid = StringUtils.join(pids, ",");
        String bookContentPname = StringUtils.join(pidNames, ",");
        Collections.reverse(pidNames);
        String bookContentName = StringUtils.join(pidNames, "-");
        // 名称： 所属 phase + subject + version + bookName(semesterName)
        // + bookcontentName
        String is = phaseName + "-" + subjectName + "-" + versionName + "-" + semesterName + "-" + bookContentName;
        resourceBookContent.setBookContentName(is);

        resourceBookContent.setBookContentPid(bookContentPid);
        resourceBookContent.setBookContentPname(bookContentPname);
        yxyResResourceBookContentRepository.save(resourceBookContent);
    }

    /**
     * 递归获取所有的父级
     */
    private List<YxyResBookContents> loopPids(String bookContentId, List<YxyResBookContents> parent) {
        YxyResBookContents bookContents = yrbcr.findById(bookContentId);
        if (bookContents != null) {
            parent.add(bookContents);
            loopPids(bookContents.getpId(), parent);
        }
        return parent;
    }

    @Override
    public Page<ElasticYxyResResource> getPage(BoolQueryBuilder boolQueryBuilder, Pageable pageable) {
        SearchQuery query = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(boolQueryBuilder).build();
        Page<ElasticYxyResResource> page = et.queryForPage(query, ElasticYxyResResource.class);
        return page;
    }

    @Override
    public List<UploadResp> lectureResourceAdd(List<ResourceReqModel> resources, int size, String bookcontentsId,
            Integer viewScope, String intro, String userId, String schoolId, String provinceCode, String cityCode,
            String districtCode, String schoolNick, String userNick) throws Exception {
        // 作者
        String author = userNick;
        List<UploadResp> list = new ArrayList<>();
        for (ResourceReqModel resourceReqModel : resources) {
            // 封面
            String extension = StringUtils.substringAfterLast(resourceReqModel.location, ".");
            // 类型
            String typeId = resourceReqModel.type;
            YxyResType resour = yxyResTypeRepository.findById(typeId);
            String typeName = resour.getName();
            // 格式
            String formatId = "";
            String formatName = "";
            YxyResFormat format = yrfr.findByExtensionContaining(extension.toLowerCase());
            if (format != null) {
                formatId = format.getId();
                formatName = format.getName();
            } else {
                formatId = "FMT06";
                formatName = "其他";
            }
            YxyResResource rYxyResResource = null;
            List<YxyResResource> uploadTimeAsc = yrrrRepository.findByMd5OrderByUploadTimeAsc(resourceReqModel.md5);
            if (CollectionUtils.isNotEmpty(uploadTimeAsc)) {
                rYxyResResource = uploadTimeAsc.get(0);
            }
            Integer converStatus = 0;
            if (rYxyResResource != null) {
                converStatus = rYxyResResource.getConvertStatus() == 2 ? rYxyResResource.getConvertStatus() : 0;
            }

            YxyResResource resource = new YxyResResource();
            resource.setConvertStatus(converStatus);
            resource.setAuthor(author);
            resource.setUploaderId(userId);
            resource.setUploaderName(userNick);
            resource.setUploaderSchoolId(schoolId);
            resource.setUploaderSchoolName(schoolNick);
            resource.setIntro(null);
            resource.setTitle(resourceReqModel.title);
            resource.setExtension(extension);
            resource.setMd5(resourceReqModel.md5);
            resource.setUploadTime(new Date());
            resource.setDownloadCount(0l);
            resource.setPv(0L);
            resource.setFavoriteCount(0l);
            resource.setIsDelete(0);
            resource.setDuration(resourceReqModel.duration);
            resource.setCreatedBy(userId);
            resource.setLastModifiedBy(userId);
            resource.setFileSize(Integer.parseInt(resourceReqModel.size + ""));
            resource.setViewScope(viewScope);
            resource.setIntro(intro);
            Integer status = 0;
            Integer isYxYunRes = 0;

            // 如果是当前指定学校默认审核通过并且是云校资源
            if (StringUtils.equals(schoolId, SystemConstant.YUNXIAO_SCHOOL_ID)) {
                // 默认审核通过
                status = 1;
                // 云校资源
                isYxYunRes = 1;
            }
            // 默认图片
            resource.setIsYxYunRes(isYxYunRes);
            resource.setIsYxView(0);
            resource.setStatus(status);
            resource.setConvertStatus(0);
            resource.setLocation(resourceReqModel.location);
            resource.setProvinceCode(provinceCode);
            resource.setCityCode(cityCode);
            resource.setDistrictCode(districtCode);
            resource.setMark(0f);
            if (typeId.equals("yx14")) {
                resource.setCover(WeikeCoverUntil.getCover(""));
            }
            resource.setTypeId(typeId);
            resource.setTypeName(typeName);
            resource.setFormatId(formatId);
            resource.setFormatName(formatName);
            resource = yrrrRepository.save(resource);
            UploadResp model = new UploadResp();
            model.resourceId = resource.getId();
            model.formatId = resource.getFormatId();
            model.resourceName = resource.getTitle();
            model.resourceUrl = resource.getLocation();
            if (typeId.equals("yx14")) {
                List<Integer> knowIds = resourceReqModel.knoledgeList;
                List<YxyQuesKnow> knowList = yxyQuesKnowRepository.findByIdIn(knowIds);
                for (YxyQuesKnow yxyQuesKnow : knowList) {
                    YxyResWeikeKnow weiKe = new YxyResWeikeKnow();
                    weiKe.setKnowId(yxyQuesKnow.getId());
                    YxyQuesKnow know = yxyQuesKnowRepository.findById(yxyQuesKnow.getParentId());
                    String twoId = know.getId() + "";
                    weiKe.setKnowTwoLevelId(twoId);
                    weiKe.setKnowTwoLevelName(know.getName());
                    YxyQuesKnow knowOne = yxyQuesKnowRepository.findById(know.getParentId());
                    String oneId = knowOne.getId() + "";
                    weiKe.setKnowOneLevelId(oneId);
                    weiKe.setKnowOneLevelName(knowOne.getName());
                    YxyResSubject yxyResSubject = yxyResSubjectRepository.findById(yxyQuesKnow.getSubject());
                    weiKe.setWeikeId(resource.getId());
                    weiKe.setStage(yxyQuesKnow.getStage());
                    // YxySubject sub =
                    // yxySubjectRepository.findByStageAndName(yxyQuesKnow.getStage(),
                    // yxyResSubject.getName());
                    weiKe.setWeikeSubject(yxyQuesKnow.getSubject());
                    weiKe.setKnowName(yxyQuesKnow.getName());
                    weiKe.setWeikeSubjectName(yxyResSubject.getName());
                    YxyResPhase yxyResPhase = yxyResPhaseRepository.findById(yxyQuesKnow.getStage());
                    weiKe.setStageName(yxyResPhase.getName());
                    weiKe.setWeiKeStatus(1);
                    yxyResWeikeKnowRepository.save(weiKe);
                }
            }
            // ### 关联目录
            saveResBookContent(resource.getId(), bookcontentsId);
            // 通知ES创建索引
            EsResourceUpdateUtil.updateEsResoure(resource.getId());
            // ##
            // ### 增加备课资源
            YxyLectureRes lectureRes = new YxyLectureRes();
            lectureRes.setUserId(userId);
            lectureRes.setSchoolId(schoolId);

            YxyResBookContents bookContents = yrbcr.findById(bookcontentsId);
            Assert.notNull(bookContents, "目录未找到请刷新页面");
            YxyResBook book = yxyResBookRepository.findById(bookContents.getBookId());
            Assert.notNull(book, "书籍未找到请刷新页面");
            if (typeId.equals("yx14")) {
                lectureRes.setResType(1);
            } else {
                lectureRes.setResType(0);
            }
            lectureRes.setFormatId(formatId);
            lectureRes.setPhaseId(book.getPhaseId());
            lectureRes.setPhaseName(book.getPhaseName());
            lectureRes.setSubjectId(book.getSubjectId());
            lectureRes.setSubjectName(book.getSubjectName());
            lectureRes.setVersionId(book.getVersionId());
            lectureRes.setVersionName(book.getVersionName());
            lectureRes.setSemesterId(book.getSemersterId());
            lectureRes.setSemesterName(book.getSemersterName());
            // FIXME BookContentsID 是存放全路径 还是存放单个
            lectureRes.setBookcontentsId(bookcontentsId);
            lectureRes.setResourceId(resource.getId());
            lectureRes.setResName(resourceReqModel.title);
            lectureRes.setResUploader(userNick);
            lectureRes.setResSchool(schoolNick);
            lectureRes.setIsDelete(0);
            lectureRes.setFileSize(Integer.parseInt(resourceReqModel.size + ""));
            lectureRes.setTypeId(typeId);
            lectureRes.setStatus(1);
            yxyLectureResRepository.save(lectureRes);
            list.add(model);
        }

        return list;
    }

    @Override
    public BoolQueryBuilder lectureResourceAreaBool(BoolQueryBuilder boolQueryBuilder, String areaId, String type,
            String format) {

        // 刨除已删除的
        TermQueryBuilder builderStatus = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatus);

        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope
        TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderviewScope);

        // 是否云校资源 isYxYunRes
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);

        // 区域
        BoolQueryBuilder areBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderprovince = new TermQueryBuilder("provinceCode", areaId);
        TermQueryBuilder buildercity = new TermQueryBuilder("cityCode", areaId);
        TermQueryBuilder builderdistrict = new TermQueryBuilder("districtCode", areaId);
        areBuilder.should(builderprovince);
        areBuilder.should(buildercity);
        areBuilder.should(builderdistrict);
        boolQueryBuilder.must(areBuilder);

        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            boolQueryBuilder.must(builder);
        }
        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            boolQueryBuilder.must(builder);
        }
        return boolQueryBuilder;
    }

    @Override
    public BoolQueryBuilder get(BoolQueryBuilder boolQueryBuilder, String bookcontent, String bookId, String phase,
            String subject, String version, String semester) {

        BoolQueryBuilder shouldBoolQueryBuilder = new BoolQueryBuilder();

        BoolQueryBuilder typeBoolQueryBuilder = new BoolQueryBuilder();

        // ## 微课
        List<YxyResBookContents> yxyResBookContents = new ArrayList<YxyResBookContents>();
        List<String> bookContentIds = new ArrayList<String>();
        if (StringUtils.isNotBlank(bookcontent)) {
            YxyResBookContents bookContents = yrbcr.findById(bookcontent);
            if (bookContents != null) {
                yxyResBookContents.add(bookContents);
            }
        } else {
            yxyResBookContents = yrbcr.findByBookIdAndIsViewOrderByOrderNum(bookId, 1);
        }
        for (YxyResBookContents yxyResBookContents2 : yxyResBookContents) {
            List<String> list = yxyResUtil.findTocByTocParent(yxyResBookContents2.getId());
            bookContentIds.addAll(list);
        }
        List<Integer> knowIds = new ArrayList<Integer>();
        if (bookContentIds.size() > 0) {
            List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                    .findByBookContentIdIn(bookContentIds);
            knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
        }
        if (knowIds.size() == 0) {
            knowIds.add(910000000);
        }
        TermsQueryBuilder kNbuilder = new TermsQueryBuilder("knowIds", knowIds);
        typeBoolQueryBuilder.must(kNbuilder);
        shouldBoolQueryBuilder.should(typeBoolQueryBuilder);

        BoolQueryBuilder reBoolQueryBuilder = new BoolQueryBuilder();

        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            reBoolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            reBoolQueryBuilder.must(builder);
        }
        // 版本
        if (StringUtils.isNotBlank(version) && !StringUtils.equals("all", version)) {
            TermQueryBuilder builder = new TermQueryBuilder("versionIdList", version);
            reBoolQueryBuilder.must(builder);
        }
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookcontent);
            BoolQueryBuilder tocBuilder = new BoolQueryBuilder();
            for (String string : tocIdList) {
                TermQueryBuilder buildertocId = new TermQueryBuilder("bookContentIdList", string);
                tocBuilder.should(buildertocId);
            }
            if (tocIdList.size() > 0) {
                reBoolQueryBuilder.must(tocBuilder);
            }
        }
        // semester 侧别
        if (StringUtils.isNotBlank(semester) && !StringUtils.equals("all", semester)) {
            TermQueryBuilder builder = new TermQueryBuilder("semesterIdList", semester);
            reBoolQueryBuilder.must(builder);
        }
        // 课本
        if (StringUtils.isNotBlank(bookId) && !StringUtils.equals("all", bookId)) {
            TermQueryBuilder builder = new TermQueryBuilder("bookIdList", bookId);
            reBoolQueryBuilder.must(builder);
        }
        shouldBoolQueryBuilder.should(reBoolQueryBuilder);

        boolQueryBuilder.must(shouldBoolQueryBuilder);

        return boolQueryBuilder;
    }

    @Override
    public BoolQueryBuilder lectureResourceSchoolBool(BoolQueryBuilder boolQueryBuilder, String SchoolId, String format,
            String type) {
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        BoolQueryBuilder viewScopeOrQuery = new BoolQueryBuilder();
        TermQueryBuilder builderviewScope1 = new TermQueryBuilder("viewScope", 1);
        TermQueryBuilder builderviewScope2 = new TermQueryBuilder("viewScope", 2);
        viewScopeOrQuery.should(builderviewScope1);
        viewScopeOrQuery.should(builderviewScope2);
        boolQueryBuilder.must(viewScopeOrQuery);

        Assert.notNull(StringUtils.defaultIfBlank(SchoolId, null), "请关联学校");
        // 学校
        TermQueryBuilder builderSchoolId = new TermQueryBuilder("uploaderSchoolId", SchoolId);
        boolQueryBuilder.must(builderSchoolId);

        // 是否云校资源 isYxYunRes 不是云校资源
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            boolQueryBuilder.must(builder);
        }

        // ####
        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            boolQueryBuilder.must(builder);
        }

        return boolQueryBuilder;
    }

    @Override
    public BoolQueryBuilder lectureResourceYunBool(BoolQueryBuilder boolQueryBuilder, String format, String type) {
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // ##
        // 是云校资源 isYxYunRes
        BoolQueryBuilder boolYun = new BoolQueryBuilder();
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 1);
        boolYun.should(builderisYxYunRes);
        // 或者在云校显示
        TermQueryBuilder builderisviewYun = new TermQueryBuilder("isYxView", 1);
        boolYun.should(builderisviewYun);
        boolQueryBuilder.must(boolYun);
        // ###
        // 刨除是私有的和在学校显示的
        int[] arr = { 0, 1 };
        TermsQueryBuilder builderViewScop = new TermsQueryBuilder("viewScope", arr);
        boolQueryBuilder.mustNot(builderViewScop);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            boolQueryBuilder.must(builder);
        }

        // ####
        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            boolQueryBuilder.must(builder);
        }
        return boolQueryBuilder;
    }

    @Override
    public BoolQueryBuilder lectureResourceUserBool(BoolQueryBuilder boolQueryBuilder, String userId, String schoolId,
            String format, String type) {
        // 上传者
        TermQueryBuilder builderUser = new TermQueryBuilder("uploaderId", userId);
        boolQueryBuilder.must(builderUser);
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);
        Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "请关联学校");
        // 学校
        TermQueryBuilder builderSchoolId = new TermQueryBuilder("uploaderSchoolId", schoolId);
        boolQueryBuilder.must(builderSchoolId);

        // 是否云校资源 isYxYunRes 不是云校资源
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);

        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            boolQueryBuilder.must(builder);
        }
        // ###
        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            boolQueryBuilder.must(builder);
        } else {
            // 刨除微课的
            TermQueryBuilder builderWeike = new TermQueryBuilder("typeId", "yx14");
            boolQueryBuilder.mustNot(builderWeike);
        }
        return boolQueryBuilder;
    }

    @Override
    public Page<ElasticYxyResResource> lectureResourceArea(boolean jingRes, String vipCondition, String areaId,
            Integer resType, String phase, String subject, String version, String bookcontent, String semester,
            String bookId, String type, String format, String keyword, Type phrase, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

        BoolQueryBuilder minBoolQueryBuilder = new BoolQueryBuilder();
        // 查询精品资源
        if (jingRes) {
            TermQueryBuilder builderJing = new TermQueryBuilder("isHighQualityYx", 1);
            boolQueryBuilder.must(builderJing);
        }
        if (vipCondition.equals("vip")) {
            // 查询VIP的
            TermQueryBuilder builderVip = new TermQueryBuilder("isVip", true);
            boolQueryBuilder.must(builderVip);
        } else if (vipCondition.equals("free")) {
            // 查询非VIP的
            TermQueryBuilder builderVip = new TermQueryBuilder("isVip", false);
            boolQueryBuilder.must(builderVip);
        }
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);

        // 类别 viewScope
        TermQueryBuilder builderviewScope = new TermQueryBuilder("viewScope", 2);
        boolQueryBuilder.must(builderviewScope);

        // 是否云校资源 isYxYunRes
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);

        // 区域
        BoolQueryBuilder areBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderprovince = new TermQueryBuilder("provinceCode", areaId);
        TermQueryBuilder buildercity = new TermQueryBuilder("cityCode", areaId);
        TermQueryBuilder builderdistrict = new TermQueryBuilder("districtCode", areaId);
        areBuilder.should(builderprovince);
        areBuilder.should(buildercity);
        areBuilder.should(builderdistrict);
        boolQueryBuilder.must(areBuilder);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            boolQueryBuilder.must(builder);
        }
        // 如果是查询微课
        if ("yx14".equals(type) || StringUtils.isBlank(type) || "all".equals(type)) {
            // 微课知识点
            BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
            if (StringUtils.isBlank(bookcontent)) {
                List<String> listcoContents = yrbcr.findIdByBookId(bookId);
                if (CollectionUtils.isNotEmpty(listcoContents)) {
                    List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                    Set<Integer> set = new HashSet<>(list1);
                    List<Integer> list = new ArrayList<>(set);
                    BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                    TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
                    TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
                    TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
                    knoBuilder.should(builderknowOne);
                    knoBuilder.should(builderknowTwo);
                    knoBuilder.should(builderknowThree);
                    knoBoolQueryBuilder.must(knoBuilder);
                }
                // 目录不为空 根据目录找到知识点
            } else {
                List<String> list = yxyResUtil.findTocByTocParent(bookcontent);
                List<Integer> knowIds = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(list)) {
                    List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                            .findByBookContentIdIn(list);
                    knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(knowIds)) {
                    knowIds.add(0000);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                knoBoolQueryBuilder.must(knoBuilder);
            }
            minBoolQueryBuilder.should(knoBoolQueryBuilder);
        }
        BoolQueryBuilder resBoolQueryBuilder = new BoolQueryBuilder();
        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            resBoolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            resBoolQueryBuilder.must(builder);
        }
        // 版本
        if (StringUtils.isNotBlank(version) && !StringUtils.equals("all", version)) {
            TermQueryBuilder builder = new TermQueryBuilder("versionIdList", version);
            resBoolQueryBuilder.must(builder);
        }
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookcontent);
            if (tocIdList.size() > 0) {
                TermsQueryBuilder builder = new TermsQueryBuilder("bookContentIdList", tocIdList);
                resBoolQueryBuilder.must(builder);
            }
        }
        // semester 侧别
        if (StringUtils.isNotBlank(semester) && !StringUtils.equals("all", semester)) {
            TermQueryBuilder builder = new TermQueryBuilder("semesterIdList", semester);
            resBoolQueryBuilder.must(builder);
        }

        // 课本
        if (StringUtils.isNotBlank(bookId) && !StringUtils.equals("all", bookId)) {
            TermQueryBuilder builder = new TermQueryBuilder("bookIdList", bookId);
            resBoolQueryBuilder.must(builder);
        }

        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            boolQueryBuilder.must(builder);
        }

        // 资源
        minBoolQueryBuilder.should(resBoolQueryBuilder);
        boolQueryBuilder.must(minBoolQueryBuilder);

        Page<ElasticYxyResResource> page = getPageEs(boolQueryBuilder, keyword, pageable);

        return page;
    }

    @Override
    public Page<ElasticYxyResResource> getPageEs(BoolQueryBuilder maxBoolQueryBuilder, String keyword,
            Pageable pageable) {
        BoolQueryBuilder b1 = new BoolQueryBuilder();
        b1.must(maxBoolQueryBuilder);
        Page<ElasticYxyResResource> page = null;
        if (StringUtils.isNotBlank(keyword)) {
            if (StringUtils.isNotBlank(keyword) && !StringUtils.equals("all", keyword)) {
                b1 = keyword(keyword, 1, b1);
            }
            page = getPage(b1, pageable);
            if (page.getContent().size() == 0 && StringUtils.isNotBlank(keyword)) {
                BoolQueryBuilder b2 = new BoolQueryBuilder();
                b2.must(maxBoolQueryBuilder);
                b2 = keyword(keyword, 2, b2);
                SearchQuery query2 = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(b2).build();
                page = et.queryForPage(query2, ElasticYxyResResource.class);
                if (page.getContent().size() == 0) {
                    BoolQueryBuilder b4 = new BoolQueryBuilder();
                    b4.must(maxBoolQueryBuilder);
                    b4 = keyword(keyword, 4, b4);
                    SearchQuery query4 = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(b4).build();
                    page = et.queryForPage(query4, ElasticYxyResResource.class);
                    if (page.getContent().size() == 0) {
                        BoolQueryBuilder b3 = new BoolQueryBuilder();
                        b3.must(maxBoolQueryBuilder);
                        b3 = keyword(keyword, 3, b3);
                        SearchQuery query3 = new NativeSearchQueryBuilder().withPageable(pageable).withQuery(b3)
                                .build();
                        page = et.queryForPage(query3, ElasticYxyResResource.class);
                    }
                }
            }
        } else {
            page = getPage(b1, pageable);
        }
        return page;
    }

    @Override
    public BoolQueryBuilder keyword(String keyword, Integer type, BoolQueryBuilder builder) {
        if (StringUtils.isNotBlank(keyword) && keyword.length() == 1) {
            RegexpQueryBuilder builderK = new RegexpQueryBuilder("title",
                    SystemConstant.RESOURCE_PREFIX + keyword + SystemConstant.RESOURCE_SUFFIX);
            builder.must(builderK);
        } else {
            if (type == 1) {
                MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", keyword).type(Type.PHRASE);
                builder.must(matchQueryBuilder);
            } else if (type == 2) {
                MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("title", keyword);
                builder.must(matchQueryBuilder);
            } else if (type == 4) {
                RegexpQueryBuilder matchQueryBuilder = new RegexpQueryBuilder("title",
                        SystemConstant.RESOURCE_PREFIX + keyword + SystemConstant.RESOURCE_SUFFIX);
                builder.must(matchQueryBuilder);
            } else {
                BoolQueryBuilder keywordBoolQueryBuilder = new BoolQueryBuilder();
                char[] key = keyword.toCharArray();
                for (char c : key) {
                    RegexpQueryBuilder builderK = new RegexpQueryBuilder("title",
                            SystemConstant.RESOURCE_PREFIX + c + SystemConstant.RESOURCE_SUFFIX);
                    keywordBoolQueryBuilder.should(builderK);
                }
                builder.must(keywordBoolQueryBuilder);
            }
        }

        return builder;
    }

    @Override
    public Page<ElasticYxyResResource> lectureResourceSchool(boolean jingRes, String vipCondition, String schoolId,
            Integer resType, String phase, String subject, String version, String bookcontent, String semester,
            String bookId, String type, String format, String keyword, Type phrase, Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        BoolQueryBuilder minBoolQueryBuilder = new BoolQueryBuilder();
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);
        // 查询精品资源
        if (jingRes) {
            TermQueryBuilder builderJing = new TermQueryBuilder("isHighQualityYx", 1);
            boolQueryBuilder.must(builderJing);
        }
        if (vipCondition.equals("vip")) {
            // 查询VIP的
            TermQueryBuilder builderVip = new TermQueryBuilder("isVip", true);
            boolQueryBuilder.must(builderVip);
        } else if (vipCondition.equals("free")) {
            // 查询非VIP的
            TermQueryBuilder builderVip = new TermQueryBuilder("isVip", false);
            boolQueryBuilder.must(builderVip);
        }
        // 类别 viewScope 本校或者是教育云
        BoolQueryBuilder viewScopeOrQuery = new BoolQueryBuilder();
        TermQueryBuilder builderviewScope1 = new TermQueryBuilder("viewScope", 1);
        TermQueryBuilder builderviewScope2 = new TermQueryBuilder("viewScope", 2);
        viewScopeOrQuery.should(builderviewScope1);
        viewScopeOrQuery.should(builderviewScope2);
        boolQueryBuilder.must(viewScopeOrQuery);

        Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "请关联学校");
        // 学校
        TermQueryBuilder builderSchoolId = new TermQueryBuilder("uploaderSchoolId", schoolId);
        boolQueryBuilder.must(builderSchoolId);

        // 是否云校资源 isYxYunRes 不是云校资源
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        boolQueryBuilder.must(builderStatusYes1);

        //
        BoolQueryBuilder resBoolQueryBuilder = new BoolQueryBuilder();
        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            resBoolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            resBoolQueryBuilder.must(builder);
        }
        // 版本
        if (StringUtils.isNotBlank(version) && !StringUtils.equals("all", version)) {
            TermQueryBuilder builder = new TermQueryBuilder("versionIdList", version);
            resBoolQueryBuilder.must(builder);
        }
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookcontent);
            if (tocIdList.size() > 0) {
                TermsQueryBuilder builder = new TermsQueryBuilder("bookContentIdList", tocIdList);
                resBoolQueryBuilder.must(builder);
            }
        }
        // semester 侧别
        if (StringUtils.isNotBlank(semester) && !StringUtils.equals("all", semester)) {
            TermQueryBuilder builder = new TermQueryBuilder("semesterIdList", semester);
            resBoolQueryBuilder.must(builder);
        }

        // 课本
        if (StringUtils.isNotBlank(bookId) && !StringUtils.equals("all", bookId)) {
            TermQueryBuilder builder = new TermQueryBuilder("bookIdList", bookId);
            resBoolQueryBuilder.must(builder);
        }
        minBoolQueryBuilder.should(resBoolQueryBuilder);
        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            boolQueryBuilder.must(builder);
        }

        // 如果是查询微课
        if ("yx14".equals(type) || StringUtils.isBlank(type) || "all".equals(type)) {
            // 微课知识点
            BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
            if (StringUtils.isBlank(bookcontent)) {
                // 根据课本Id拿到所有目录id
                List<String> listcoContents = yrbcr.findIdByBookId(bookId);
                // 根据目录Id拿到所有的知识点Id
                if (CollectionUtils.isNotEmpty(listcoContents)) {
                    List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                    Set<Integer> set = new HashSet<>(list1);
                    List<Integer> list = new ArrayList<>(set);
                    BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                    TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
                    TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
                    TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
                    knoBuilder.should(builderknowOne);
                    knoBuilder.should(builderknowTwo);
                    knoBuilder.should(builderknowThree);
                    knoBoolQueryBuilder.must(knoBuilder);
                }
                // 目录不为空 根据目录找到知识点
            } else {
                List<String> list = yxyResUtil.findTocByTocParent(bookcontent);
                List<Integer> knowIds = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(list)) {
                    List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                            .findByBookContentIdIn(list);
                    knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(knowIds)) {
                    knowIds.add(0000);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                knoBoolQueryBuilder.must(knoBuilder);
            }
            minBoolQueryBuilder.should(knoBoolQueryBuilder);
        }

        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            boolQueryBuilder.must(builder);
        }

        boolQueryBuilder.must(minBoolQueryBuilder);

        Page<ElasticYxyResResource> page = getPageEs(boolQueryBuilder, keyword, pageable);
        return page;
    }

    @Override
    public Page<ElasticYxyResResource> lectureResourceYun(boolean jingRes, String vipCondition, Integer resType,
            String phase, String subject, String version, String bookcontent, String semester, String bookId,
            String type, String format, String keyword, Type phrase, Pageable pageable) {
        long start = System.currentTimeMillis();
        //
        BoolQueryBuilder maxBoolQueryBuilder = new BoolQueryBuilder();

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 查询精品资源
        if (jingRes) {
            TermQueryBuilder builderJing = new TermQueryBuilder("isHighQualityYx", 1);
            maxBoolQueryBuilder.must(builderJing);
        }
        if (vipCondition.equals("vip")) {
            // 查询VIP的
            TermQueryBuilder builderVip = new TermQueryBuilder("isVip", true);
            maxBoolQueryBuilder.must(builderVip);
        } else if (vipCondition.equals("free")) {
            // 查询非VIP的
            TermQueryBuilder builderVip = new TermQueryBuilder("isVip", false);
            maxBoolQueryBuilder.must(builderVip);
        }
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        maxBoolQueryBuilder.must(builderDel);

        // ##
        // 是云校资源 isYxYunRes
        // BoolQueryBuilder boolYun = new BoolQueryBuilder();
        // TermQueryBuilder builderisYxYunRes = new
        // TermQueryBuilder("isYxYunRes", 1);
        // boolYun.should(builderisYxYunRes);
        // // 或者在云校显示
        // TermQueryBuilder builderisviewYun = new TermQueryBuilder("isYxView",
        // 1);
        // boolYun.should(builderisviewYun);
        maxBoolQueryBuilder.must(new TermQueryBuilder("isYxView", 1));
        //

        // 刨除是私有的 和在学校展示的
        int[] arr = { 0, 1 };
        TermsQueryBuilder builderViewScop = new TermsQueryBuilder("viewScope", arr);
        maxBoolQueryBuilder.mustNot(builderViewScop);

        // 只查询审核已通过的
        TermQueryBuilder builderStatusYes1 = new TermQueryBuilder("status", 1);
        maxBoolQueryBuilder.must(builderStatusYes1);

        // 资源类型
        BoolQueryBuilder resBoolQueryBuilder = new BoolQueryBuilder();

        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            resBoolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            resBoolQueryBuilder.must(builder);
        }
        // 版本
        if (StringUtils.isNotBlank(version) && !StringUtils.equals("all", version)) {
            TermQueryBuilder builder = new TermQueryBuilder("versionIdList", version);
            resBoolQueryBuilder.must(builder);
        }
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            long startBp = System.currentTimeMillis();
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookcontent);
            if (tocIdList.size() > 0) {
                TermsQueryBuilder builder = new TermsQueryBuilder("bookContentIdList", tocIdList);
                resBoolQueryBuilder.must(builder);
            }
            long endBp = System.currentTimeMillis();
            LOGGER.info("根据目录查询子目录时间为：" + ((endBp - startBp) / 1000));
            // for (String string : tocIdList) {
            // TermQueryBuilder buildertocId = new
            // TermQueryBuilder("bookContentIdList", string);
            // tocBuilder.should(buildertocId);
            // }

        }
        // semester 侧别
        if (StringUtils.isNotBlank(semester) && !StringUtils.equals("all", semester)) {
            TermQueryBuilder builder = new TermQueryBuilder("semesterIdList", semester);
            resBoolQueryBuilder.must(builder);
        }
        // 课本
        if (StringUtils.isNotBlank(bookId) && !StringUtils.equals("all", bookId)) {
            TermQueryBuilder builder = new TermQueryBuilder("bookIdList", bookId);
            resBoolQueryBuilder.must(builder);
        }
        //
        boolQueryBuilder.should(resBoolQueryBuilder);

        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            maxBoolQueryBuilder.must(builder);
        }
        // 如果是查询微课
        if (StringUtils.isBlank(type) || StringUtils.equals("all", type) || StringUtils.equals("yx14", type)) {
            // 微课知识点
            BoolQueryBuilder knoBoolQueryBuilder = new BoolQueryBuilder();
            if (StringUtils.isBlank(bookcontent)) {
                long startXX = System.currentTimeMillis();
                // 根据课本Id拿到所有目录id
                List<String> listcoContents = yrbcr.findIdByBookId(bookId);
                // 根据目录Id拿到所有的知识点Id
                if (CollectionUtils.isNotEmpty(listcoContents)) {
                    List<Integer> list1 = yxyResBookContentsKnoledgesRepository.findKonwId(listcoContents);
                    Set<Integer> set = new HashSet<>(list1);
                    List<Integer> list = new ArrayList<>(set);
                    BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                    TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", list);
                    TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", list);
                    TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", list);
                    knoBuilder.should(builderknowOne);
                    knoBuilder.should(builderknowTwo);
                    knoBuilder.should(builderknowThree);
                    knoBoolQueryBuilder.must(knoBuilder);
                }
                long endXX = System.currentTimeMillis();
                LOGGER.info(("根据书籍找知识点时间为：" + ((endXX - startXX) / 1000)));
                // 目录不为空 根据目录找到知识点
            } else {
                long startAA = System.currentTimeMillis();
                List<String> list = yxyResUtil.findTocByTocParent(bookcontent);
                List<Integer> knowIds = new ArrayList<Integer>();
                if (CollectionUtils.isNotEmpty(list)) {
                    List<YxyResBookContentsKnoledges> knowList = yxyResBookContentsKnoledgesRepository
                            .findByBookContentIdIn(list);
                    knowIds = knowList.stream().map(x -> x.getKnowledgeId()).collect(Collectors.toList());
                }
                if (CollectionUtils.isEmpty(knowIds)) {
                    knowIds.add(0000);
                }
                BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
                TermsQueryBuilder builderknowOne = new TermsQueryBuilder("knowIds", knowIds);
                TermsQueryBuilder builderknowTwo = new TermsQueryBuilder("knowOneLevelIds", knowIds);
                TermsQueryBuilder builderknowThree = new TermsQueryBuilder("knowTwoLevelIds", knowIds);
                knoBuilder.should(builderknowOne);
                knoBuilder.should(builderknowTwo);
                knoBuilder.should(builderknowThree);
                knoBoolQueryBuilder.must(knoBuilder);
                long endAA = System.currentTimeMillis();
                LOGGER.info("根据目录找知识点时间为:" + ((endAA - startAA) / 1000));
            }
            boolQueryBuilder.should(knoBoolQueryBuilder);
        }
        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            maxBoolQueryBuilder.must(builder);
        }
        maxBoolQueryBuilder.must(boolQueryBuilder);

        Page<ElasticYxyResResource> page = getPageEs(maxBoolQueryBuilder, keyword, pageable);
        long end = System.currentTimeMillis();
        LOGGER.info("查询总时长为：" + ((end - start) / 1000));
        return page;
    }

    @Override
    public Page<ElasticYxyResResource> lectureResourceMy(boolean jingRes, String vipCondition, String userId,
            String schoolId, Integer resType, String phase, String subject, String version, String bookcontent,
            String semester, String bookId, String type, String format, String keyword, Type searchType,
            Pageable pageable) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 上传者
        TermQueryBuilder builderUser = new TermQueryBuilder("uploaderId", userId);
        boolQueryBuilder.must(builderUser);
        // 查询精品资源
        if (jingRes) {
            TermQueryBuilder builderJing = new TermQueryBuilder("isHighQualityYx", 1);
            boolQueryBuilder.must(builderJing);
        }
        if (vipCondition.equals("vip")) {
            // 查询VIP的
            TermQueryBuilder builderVip = new TermQueryBuilder("isVip", true);
            boolQueryBuilder.must(builderVip);
        } else if (vipCondition.equals("free")) {
            // 查询非VIP的
            TermQueryBuilder builderVip = new TermQueryBuilder("isVip", false);
            boolQueryBuilder.must(builderVip);
        }
        // 刨除已删除的
        TermQueryBuilder builderDel = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderDel);
        Assert.notNull(StringUtils.defaultIfBlank(schoolId, null), "请关联学校");
        // 学校
        TermQueryBuilder builderSchoolId = new TermQueryBuilder("uploaderSchoolId", schoolId);
        boolQueryBuilder.must(builderSchoolId);

        // 是否云校资源 isYxYunRes 不是云校资源
        TermQueryBuilder builderisYxYunRes = new TermQueryBuilder("isYxYunRes", 0);
        boolQueryBuilder.must(builderisYxYunRes);
        // 学段
        if (StringUtils.isNotBlank(phase) && !StringUtils.equals("all", phase)) {
            TermQueryBuilder builder = new TermQueryBuilder("phaseIdList", phase);
            boolQueryBuilder.must(builder);
        }
        // 学科
        if (StringUtils.isNotBlank(subject) && !StringUtils.equals("all", subject)) {
            TermQueryBuilder builder = new TermQueryBuilder("subjectIdList", subject);
            boolQueryBuilder.must(builder);
        }
        // 版本
        if (StringUtils.isNotBlank(version) && !StringUtils.equals("all", version)) {
            TermQueryBuilder builder = new TermQueryBuilder("versionIdList", version);
            boolQueryBuilder.must(builder);
        }
        // 目录
        if (StringUtils.isNotBlank(bookcontent) && !StringUtils.equals("all", bookcontent)) {
            long startBp = System.currentTimeMillis();
            List<String> tocIdList = yxyResUtil.findTocByTocParent(bookcontent);
            if (tocIdList.size() > 0) {
                TermsQueryBuilder builder = new TermsQueryBuilder("bookContentIdList", tocIdList);
                boolQueryBuilder.must(builder);
            }
            long endBp = System.currentTimeMillis();
            LOGGER.info("根据目录查询子目录时间为：" + ((endBp - startBp) / 1000));
            // for (String string : tocIdList) {
            // TermQueryBuilder buildertocId = new
            // TermQueryBuilder("bookContentIdList", string);
            // tocBuilder.should(buildertocId);
            // }

        }
        // semester 侧别
        if (StringUtils.isNotBlank(semester) && !StringUtils.equals("all", semester)) {
            TermQueryBuilder builder = new TermQueryBuilder("semesterIdList", semester);
            boolQueryBuilder.must(builder);
        }
        // 课本
        if (StringUtils.isNotBlank(bookId) && !StringUtils.equals("all", bookId)) {
            TermQueryBuilder builder = new TermQueryBuilder("bookIdList", bookId);
            boolQueryBuilder.must(builder);
        }
        // 格式
        if (StringUtils.isNotBlank(format) && !StringUtils.equals("all", format)) {
            TermQueryBuilder builder = new TermQueryBuilder("formatId", format);
            boolQueryBuilder.must(builder);
        }
        // ###
        // 类型
        if (StringUtils.isNotBlank(type) && !StringUtils.equals("all", type)) {
            TermQueryBuilder builder = new TermQueryBuilder("typeId", type);
            boolQueryBuilder.must(builder);
        } else {
            // 刨除微课的
            TermQueryBuilder builderWeike = new TermQueryBuilder("typeId", "yx14");
            boolQueryBuilder.mustNot(builderWeike);
        }
        Page<ElasticYxyResResource> page = getPageEs(boolQueryBuilder, keyword, pageable);
        return page;

    }

}
